import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:tv_friso_screen/pad/home_page_pad.dart';
import 'package:tv_friso_screen/pad/sales_page_en_pad.dart';
import 'package:tv_friso_screen/pad/sales_page_pad.dart';
import 'package:tv_friso_screen/pad/store_page_en_pad.dart';
import 'package:tv_friso_screen/pad/store_page_pad.dart';
import 'package:tv_friso_screen/utils/phone_info_utils.dart';

import '../login_phone_pad_page.dart';
import '../utils/share_pre_utils.dart';
import 'home_page_en_pad.dart';

//店主 主导页
class HomeMainPagePad extends StatefulWidget {
  const HomeMainPagePad({super.key});

  // final TabsBar tabBar;

  // const HomeMainPage({Key? key, required this.tabBar}) : super(key: key);

  @override
  State<HomeMainPagePad> createState() => _HomeMainPageState();
}

class _HomeMainPageState extends State<HomeMainPagePad>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  int _currentIndex = 0;
  double _dragStartPosition = 0.0;

  List<Widget> _pageList = [
    const HomePagePad(),
    const SalesPagePad(),
    const StorePagePad(),
  ];

  final pageController = PageController();
  var currentLanguage = '';
  Timer? downTimer; //右上角时分秒显示倒计时
  var nowTime = "";

  void countDownTimer() {
    downTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      //每隔 1 秒钟 刷新一次时分秒
      setState(() {
        nowTime = PhoneInfoUtils.getTime();
      });
    });
  }

  @override
  void initState() {
    super.initState();
    countDownTimer();
    currentLanguage = SharePreUtils.getLanguage();
    if (currentLanguage == "zh") {
      _pageList = [
        const HomePagePad(),
        const SalesPagePad(),
        const StorePagePad(),
      ];
    } else {
      _pageList = [
        const HomePageEnPad(),
        const SalesPageEnPad(),
        const StorePageEnPad(),
      ];
    }
  }

  @override
  void dispose() {
    super.dispose();
    downTimer?.cancel();
  }

  //当PageView可滑动时 会调用这个方法
  void onPageChanged(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); // 必须调用super.build(context)
    return Scaffold(
      body: Stack(
        children: [
          GestureDetector(
            onHorizontalDragStart: (details) {
              _dragStartPosition = details.localPosition.dx; // 记录起始位置
            },
            onHorizontalDragEnd: (details) {
              double dragDistance =
                  details.velocity.pixelsPerSecond.dx; // 获取滑动距离
              // 设置滑动阈值
              if (dragDistance > 10) {
                // 向右滑动，切换到上一页
                pageController.previousPage(
                  duration: const Duration(milliseconds: 300),
                  curve: Curves.easeInOut,
                );
              } else if (dragDistance < -10) {
                // 向左滑动，切换到下一页
                pageController.nextPage(
                  duration: const Duration(milliseconds: 300),
                  curve: Curves.easeInOut,
                );
              }
            },
            child: PageView(
              controller: pageController,
              // onPageChanged: onPageChanged,
              physics: const NeverScrollableScrollPhysics(), //禁止滑动
              // physics: const AlwaysScrollableScrollPhysics(),
              children: _pageList,
            ),
          ),
          GestureDetector(
            onTap: () {
              showLoginOutDialog(context);
            },
            child: Container(
              margin: EdgeInsets.only(top: 7.w, left: 45.w),
              child: Container(
                padding: EdgeInsets.only(
                    left: 20.w, right: 20.w, top: 15.w, bottom: 15.w),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8.w),
                  border: Border.all(
                    color: const Color(0xFF829EEE),
                    width: 1.w,
                  ),
                ),
                child: Text(
                  currentLanguage == "zh" ? "退出登录" : "Log Out",
                  style: TextStyle(
                    color: const Color(0xFF1ED2FF),
                    fontSize: ScreenUtil().setSp(18),
                    fontWeight: FontWeight.w500,
                  ),
                  textAlign: TextAlign.center,
                ),
              ),
            ),
          ),
          Positioned(
            left: 180.w,
            top: 5.w,
            child: Container(
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8.w),
                  border: Border.all(
                    color: const Color.fromRGBO(3, 90, 168, 1),
                    width: 1.w, // 边框宽度
                  )),
              child: Row(
                children: [
                  GestureDetector(
                    onTap: () {
                      SharePreUtils.setLanguage("zh");
                      setState(() {
                        currentLanguage = "zh";
                        SharePreUtils.setLanguage(currentLanguage);
                        _pageList = [
                          const HomePagePad(),
                          const SalesPagePad(),
                          const StorePagePad(),
                        ];
                      });
                    },
                    child: Container(
                      width: 150.w,
                      height: 55.w,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(8.w),
                        color: currentLanguage == "zh"
                            ? const Color.fromRGBO(30, 210, 255, 1)
                            : Colors.transparent,
                      ),
                      padding: EdgeInsets.only(top: 8.w, bottom: 8.w),
                      child: Text(
                        "中文",
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: currentLanguage == "zh"
                              ? const Color.fromRGBO(8, 42, 51, 1)
                              : const Color.fromRGBO(30, 210, 255, 1),
                          fontSize: 28.sp,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      SharePreUtils.setLanguage("en");
                      setState(() {
                        currentLanguage = "en";
                        SharePreUtils.setLanguage(currentLanguage);
                        _pageList = [
                          const HomePageEnPad(),
                          const SalesPageEnPad(),
                          const StorePageEnPad(),
                        ];
                      });
                    },
                    child: Container(
                      width: 150.w,
                      height: 55.w,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(8.w),
                        color: currentLanguage == "en"
                            ? const Color.fromRGBO(30, 210, 255, 1)
                            : Colors.transparent,
                      ),
                      padding: EdgeInsets.only(top: 8.w, bottom: 8.w),
                      child: Text(
                        "English",
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: currentLanguage == "en"
                              ? const Color.fromRGBO(8, 42, 51, 1)
                              : const Color.fromRGBO(30, 210, 255, 1),
                          fontSize: 28.sp,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
          Container(
            padding: EdgeInsets.only(top: 20.w, right: 20.w),
            height: 100.w,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Text(
                  nowTime,
                  style: TextStyle(
                    color: const Color(0xFFBDE1FF),
                    fontSize: 28.sp,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(
                  width: 20.w,
                ),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text(
                      getWeekDay(),
                      style: TextStyle(
                        color: const Color(0xFFBDE1FF),
                        fontSize: 24.sp,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Text(
                      PhoneInfoUtils.getDate(),
                      style: TextStyle(
                        color: const Color(0xFFBDE1FF),
                        fontSize: 24.sp,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void showLoginOutDialog(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (BuildContext context) {
        return StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Stack(
                children: [
                  Container(
                    alignment: Alignment.center,
                    width: 500.w,
                    height: 500.w,
                    margin: EdgeInsets.only(
                      left: 65.w,
                      right: 65.w,
                      top: 70.w,
                    ),
                    padding: EdgeInsets.only(left: 40.w, right: 40.w),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(20.w)),
                      image: const DecorationImage(
                        image: AssetImage("assets/images/icon_update_bg.png"),
                        fit: BoxFit.fill,
                      ),
                    ),
                    child: Column(
                      // crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                          height: 60.w,
                        ),
                        Text(
                          currentLanguage == "zh" ? "退出登录" : "Log out",
                          style: TextStyle(
                            fontSize: 32.sp,
                            color: const Color(0xFF00EEFF),
                            fontWeight: FontWeight.bold,
                            decoration: TextDecoration.none,
                          ),
                          textAlign: TextAlign.center,
                        ),
                        SizedBox(
                          height: 20.h,
                        ),
                        Text(
                          currentLanguage == "zh"
                              ? "确定要退出登录吗?"
                              : 'Are you sure you want to log out?',
                          softWrap: true,
                          style: TextStyle(
                            fontSize: 24.sp,
                            color: const Color(0xff8BD8DD),
                            decoration: TextDecoration.none,
                            fontWeight: FontWeight.normal,
                          ),
                          textAlign: TextAlign.start,
                        ),
                        const Spacer(),
                        Container(
                          margin: EdgeInsets.only(
                              left: 20.w, right: 20.w, bottom: 60.w),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              GestureDetector(
                                onTap: () {
                                  //回到登录页
                                  SharePreUtils.setToken("");
                                  Navigator.of(context).pushAndRemoveUntil(
                                      MaterialPageRoute(
                                          builder: (context) =>
                                              const LoginPhonePadPage()),
                                      (route) => false);
                                },
                                child: Container(
                                  padding: EdgeInsets.only(
                                      left: 40.w,
                                      right: 40.w,
                                      top: 20.w,
                                      bottom: 20.w),
                                  alignment: Alignment.center,
                                  decoration: const BoxDecoration(
                                    // borderRadius:
                                    //     BorderRadius.all(Radius.circular(20.w)),
                                    image: DecorationImage(
                                      image: AssetImage(
                                          "assets/images/icon_update_btn.png"),
                                      fit: BoxFit.fill,
                                    ),
                                  ),
                                  child: Text(
                                    currentLanguage == "zh" ? "确定" : 'OK',
                                    style: TextStyle(
                                      fontSize: 28.sp,
                                      color: Colors.white,
                                      fontWeight: FontWeight.bold,
                                      decoration: TextDecoration.none,
                                    ),
                                  ),
                                ),
                              ),
                              GestureDetector(
                                onTap: () {
                                  Navigator.pop(context);
                                },
                                child: Container(
                                  padding: EdgeInsets.only(
                                      left: 40.w,
                                      right: 40.w,
                                      top: 20.w,
                                      bottom: 20.w),
                                  alignment: Alignment.center,
                                  decoration: const BoxDecoration(
                                    // borderRadius:
                                    //     BorderRadius.all(Radius.circular(20.w)),
                                    image: DecorationImage(
                                      image: AssetImage(
                                          "assets/images/icon_update_btn.png"),
                                      fit: BoxFit.fill,
                                    ),
                                  ),
                                  child: Text(
                                    currentLanguage == "zh" ? "取消" : 'Cancel',
                                    style: TextStyle(
                                      fontSize: 28.sp,
                                      color: Colors.white,
                                      fontWeight: FontWeight.bold,
                                      decoration: TextDecoration.none,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ],
          );
        });
      },
    );
  }

  //获取周几
  String getWeekDay() {
    DateTime now = DateTime.now(); // 获取当前日期和时间
    String weekDay;
    if (currentLanguage == "zh") {
      switch (now.weekday) {
        case DateTime.monday:
          weekDay = "星期一";
          break;
        case DateTime.tuesday:
          weekDay = "星期二";
          break;
        case DateTime.wednesday:
          weekDay = "星期三";
          break;
        case DateTime.thursday:
          weekDay = "星期四";
          break;
        case DateTime.friday:
          weekDay = "星期五";
          break;
        case DateTime.saturday:
          weekDay = "星期六";
          break;
        default:
          weekDay = "星期天";
          break;
      }
    } else {
      switch (now.weekday) {
        case DateTime.monday:
          weekDay = "Monday";
          break;
        case DateTime.tuesday:
          weekDay = "Tuesday";
          break;
        case DateTime.wednesday:
          weekDay = "Wednesday";
          break;
        case DateTime.thursday:
          weekDay = "Thursday";
          break;
        case DateTime.friday:
          weekDay = "Friday";
          break;
        case DateTime.saturday:
          weekDay = "Saturday";
          break;
        default:
          weekDay = "Sunday";
          break;
      }
    }

    return weekDay;
  }
}
